<?php
//本程序将数据从mysql数据库导出，导出的语句就是sql插入语句，可以方便地导入mysql数据库
if ($argc < 2) {
    die("Usage: php getDataFromMysqlToTxt.php tableName dstFile [range_start] [range_end]");
}
else {
    $tableName = $argv[1];
    $retFile = $argv[2];
    if (!empty($argv[3])) {
        $range_start = $argv[3];
    }
    if (!empty($argv[4])) {
        $range_end = $argv[4];
    }
}
//var_dump($tableName, $retFile, $range_start, $range_end);die;
set_time_limit(0);
ini_set('memory_limit','2048M');
$length = 5000;
//$retFile = "relates_ask_150w_180w.txt"; //打开文件
if (!$file_handle = fopen($retFile, 'w+')) {
    echo "不能打开文件 $retFile";
    exit;
}
$mysqlLink = mysql_pconnect('172.16.9.36', 'babytree', 'babytree');
if (!$mysqlLink) {
        die('Could not connect: ' . mysql_error());
}
mysql_select_db("babytree", $mysqlLink);
if (empty($range_start)) {
    $countSql = "select max(discussion_id) from $tableName";
} else if (empty($range_end)) {
    $countSql = "select max(discussion_id) from $tableName where discussion_id>=".$range_start;
} else {
    $countSql = "select max(discussion_id) from $tableName where discussion_id>=".$range_start." and discussion_id <= ".$range_end;
}
$getSqlPrefix = str_replace("max(discussion_id)", "*", $countSql);
if (empty($range_end)) {
    $result = mysql_query($countSql, $mysqlLink);
    $range_end = mysql_fetch_row($result);
    $range_end = intval($range_end[0]);
}
$start = $range_start;
$del_chars = array("\x0D", "\n", "\r\n", "\t", "☆");
while ($start < $range_end) {
    $end = min($start+$length, $range_end);
    $getSql = "select * from $tableName where discussion_id>=".$start." and discussion_id < ".$end;
    $result = mysql_query($getSql, $mysqlLink);
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        if ($row['status'] != 'save') {
            continue;
        }
        $row['title'] = str_replace($del_chars, " ", strip_tags($row['title']));
        //$row['title'] = mb_convert_encoding ($row['title'], "UTF-8");
        $row['title'] = preg_replace("/&#?[a-z0-9]+\;/i","",$row['title']);
        $row['content'] = str_replace($del_chars, " ", strip_tags($row['content']));
        //$row['content'] = mb_convert_encoding ($row['content'], "UTF-8");
        $row['content'] = preg_replace("/&#?[a-z0-9]+;/i","",$row['content']);
        $itemStr = $row['discussion_id']."\t".$row['title']."\t".$row['content']."\t".$row['discussion_type']."\t".$row['associated_id']."\n";
        //$itemStr = $row['content']."\t".$row['title']."\n";
        fwrite($file_handle, $itemStr);
   }
    echo "has deal ".($length+$start)." questions!\n";
    $start = $end;
}
fclose($file_handle);
mysql_close($mysqlLink);
